﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using WsdlDiscovery.net.bing.api;
using WsdlDiscovery.localhost;

namespace WsdlDiscovery
{
    public class WsdlDiscovery : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }

        //Searches the top ten Bing results for a given string for WSDL addresses
        //taken from Bing Search API example provided by Microsoft and modified to simplify
        public string[] GetWsdlSearchResponse(string str)
        {
            //set up the services and the aggregate WSDL address array
            BingService bservice = new BingService();
            WsdlAddress wservice = new WsdlAddress();
            string[] wsdlResultsArray = new string[400];
            int wsdlResultsArrayLength = 0;

            //complete the web search
            SearchRequest request = new SearchRequest();

            request.AppId = "C92824F2D31A2EFCFC3AEC31168E9DBC5AC2DA8D";
            request.Query = str;//Bing inconveniently ignores punctuation in most cases
            request.Sources = new SourceType[] { SourceType.Web };

            request.Web = new WebRequest();
            request.Web.Count = 10;
            request.Web.CountSpecified = true;

            SearchResponse response = bservice.Search(request);

            if (str != "" && str != null)
            {
                //convert the web search results into WSDL addresses
                for (int i = 0; i < request.Web.Count; i++)
                {
                    string[] tempWsdlResultsArray = new string[100];
                    //gather WSDL addresses from each Url returned from the search
                    tempWsdlResultsArray = wservice.ReturnWsdlAddresses(response.Web.Results[i].Url);

                    //add the WSDL addresses to the aggregate array
                    for (int j = 0; j < tempWsdlResultsArray.Length; j++)
                    {
                        wsdlResultsArray[wsdlResultsArrayLength] = tempWsdlResultsArray[j];
                        wsdlResultsArrayLength++;
                    }
                }
            }
            else
            {
                wsdlResultsArray[0] = "C'mon; give me a search term.";
            }
            //send the aggregate WSDL addresses array on its way
            return wsdlResultsArray;
        }
    }
}
